package cool.tianyou.blue.bird.dialog;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;

import cool.tianyou.blue.bird.R;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class LoadingDialog extends AlertDialog {
    private final Context context;
    private final String text;
    private Integer autoDismiss;

    public LoadingDialog(@NonNull Context context, String text) {
        super(context);
        this.context = context;
        this.text = text;
    }

    public LoadingDialog setAutoDismiss(Integer autoDismiss) {
        this.autoDismiss = autoDismiss;
        return this;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.dialog_loading_layout);
        initView();
    }

    private void initView() {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // 加载布局文件
        @SuppressLint("InflateParams") View mLayout = inflater.inflate(R.layout.dialog_loading_layout, null, false);

        TextView loadingText = mLayout.findViewById(R.id.tv_loading_text);
        loadingText.setText(this.text);
        // 添加布局文件到 Dialog
        this.setContentView(mLayout);

    }

    public LoadingDialog showDialog() {
        this.show();
        return this;
    }

    @Override
    public void show() {
        this.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        Window dialogWindow = this.getWindow();

        dialogWindow.setWindowAnimations(R.style.DialogOutAndInStyle);
        super.show();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL);
        lp.width = 800; // 宽度
        dialogWindow.setAttributes(lp);
        this.setCanceledOnTouchOutside(false);

        if (this.autoDismiss != null) {
            ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
            executor.schedule(this::dismiss, autoDismiss, TimeUnit.MILLISECONDS);
        }

    }
}
